package org.axed.user.client.util;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.RootPanel;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * Watches the browser font size and alerts listeners.
 *
 * One alert will always be issued on page load (actually 1ms after it).
 */
public class FontSizeWatcher {

	static FontSizeWatcher singleton = null;
	int height = 0;
	Element testCase;
	ArrayList listeners = new ArrayList();
	
	protected FontSizeWatcher() {
		testCase = DOM.createSpan();
		DOM.setInnerText(testCase, "W");
		DOM.setStyleAttribute(testCase, "position", "absolute");
		DOM.setStyleAttribute(testCase, "left", "-1000px");
		DOM.setStyleAttribute(testCase, "top", "-1000px");
		DOM.setStyleAttribute(testCase, "fontFamily", "monospace");
		DOM.setStyleAttribute(testCase, "fontSize", "12px");
		DOM.appendChild(RootPanel.get().getElement(), testCase);

		Timer t = new Timer() {
			public void run() {
				int h = DOM.getElementPropertyInt(testCase, "offsetHeight");
				if (h != height) {
					height = h;
					for (Iterator it = listeners.iterator(); it.hasNext();) {
		      			((FontSizeListener) it.next()).onFontSizeChange(testCase);
					}
					// repair the testcase	
					DOM.setStyleAttribute(testCase, "fontFamily", "monospace");
					DOM.setStyleAttribute(testCase, "fontSize", "12px");
				}
				this.schedule(1000);
			}
		};
		t.schedule(1);
	}

	public static void addListener(FontSizeListener listener) {
		if (singleton == null) {
			singleton = new FontSizeWatcher();
		}
		singleton.listeners.add(listener);
	}

	public static void removeListener(FontSizeListener listener) {
		if (singleton == null) {
			return;
		}
		singleton.listeners.remove(listener);
	}
	
	public static Element getTestCase() {
		if (singleton == null) {
			return null;
		}
		return singleton.testCase;
	}
}
